<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
  <title>购物车</title>
  <link rel="stylesheet" href="${pageContext.request.contextPath}/css/style.css">
</head>
<body>
<div class="container">
  <h1>购物车</h1>
  <p><a href="${pageContext.request.contextPath}/products">返回商品列表</a></p>

  <c:if test="${not empty message}">
    <div class="alert success">${message}</div>
  </c:if>
  <c:if test="${not empty error}">
    <div class="alert error">${error}</div>
  </c:if>

  <c:choose>
    <c:when test="${empty sessionScope.cart || sessionScope.cart.size() == 0}">
      <p>您的购物车是空的</p>
    </c:when>
    <c:otherwise>
      <table>
        <tr>
          <th>商品名称</th>
          <th>单价</th>
          <th>数量</th>
          <th>小计</th>
          <th>操作</th>
        </tr>
        <c:forEach items="${sessionScope.cart}" var="item">
          <tr>
            <td>${item.product.name}</td>
            <td>¥${item.product.price}</td>
            <td>
              <form action="${pageContext.request.contextPath}/cart" method="post" style="display: inline;">
                <input type="hidden" name="action" value="update">
                <input type="hidden" name="productId" value="${item.product.id}">
                <input type="number" name="quantity" value="${item.quantity}"
                       min="1" max="${item.product.stock + item.quantity}">
                <button type="submit">更新</button>
              </form>
            </td>
            <td>¥${item.product.price * item.quantity}</td>
            <td>
              <form action="${pageContext.request.contextPath}/cart" method="post" style="display: inline;">
                <input type="hidden" name="action" value="remove">
                <input type="hidden" name="productId" value="${item.product.id}">
                <button type="submit">删除</button>
              </form>
            </td>
          </tr>
        </c:forEach>
        <tr>
          <td colspan="3" style="text-align: right;">总计:</td>
          <td>¥<c:set var="total" value="0" />
            <c:forEach items="${sessionScope.cart}" var="item">
              <c:set var="total" value="${total + (item.product.price * item.quantity)}" />
            </c:forEach>
              ${total}
          </td>
          <td></td>
        </tr>
      </table>

      <div class="actions">
        <form action="${pageContext.request.contextPath}/cart" method="post">
          <input type="hidden" name="action" value="clear">
          <button type="submit">清空购物车</button>
        </form>

        <form action="${pageContext.request.contextPath}/order" method="post">
          <button type="submit">生成订单</button>
        </form>
      </div>
    </c:otherwise>
  </c:choose>
</div>
</body>
</html>